package com.sxhuayuan.parking.plugin.parking.dahua;

import com.sxhuayuan.parking.config.CarActType;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

class DaHuaUtils {
	static void returnResponse(HttpServletResponse response, String result) {
		response.setHeader("content-type", "application/json;charset=UTF-8");
		try {
			PrintWriter pw = response.getWriter();
			pw.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 获取16位密钥
	private static String getSecretKey(String agent3) {
		int size = agent3.length() - 1;
		char c = '0';
		for (int i = size; i > 0; i--) {
			c = agent3.charAt(i);
			if (c >= '0' && c <= '9')
				break;
		}
		int index = Integer.parseInt(Character.toString(c));
		return agent3.substring(index, index + 16);
	}

	/**
	 * 解密具体方法
	 * @param sSrc 加密数据
	 * @param sKey 加密key
	 * @return 解密数据
	 */
	private static String Decrypt(String sSrc, String sKey) {
		// 大华将加密数据中的+ 替换成了 空格
		sSrc = sSrc.replaceAll(" ", "+");
		try {
			// 判断Key是否正确
			if (sKey == null) {
				System.out.print("Key为空null");
				return null;
			}
			// 判断Key是否为16位
			if (sKey.length() != 16) {
				System.out.print("Key长度不是16位");
				return null;
			}
			byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] encrypted1 = new Base64().decode(sSrc);// 先用base64解密
			byte[] original = cipher.doFinal(encrypted1);
			return new String(original, StandardCharsets.UTF_8);
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}

	/**
	 * 大华数据解密
	 * @return 解析完成的json
	 */
	static String decodeRequest(HttpServletRequest request) {
		String agent = request.getHeader("User-Agent");
		// 下面代码用来测试  不用加密直接传json
//		if(agent == null || agent.length()==0){
//			try {
//				return IOUtils.toString(request.getInputStream(), "utf-8");
//			} catch (IOException e) {
//				return "";
//			}
//		}
		String[] agents = agent.split("_");
		String key = DaHuaUtils.getSecretKey(agents[3]);
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String name = parameterNames.nextElement();
			if (name != null && name.length() > 0)
				return DaHuaUtils.Decrypt(name, key);
		}
		return null;
	}

	/**
	 * 根据大华车厂类型, 返回枚举
	 * @param actType 大华车厂类型 (0 长期车,类似内部, 1 临时车  2免费车)
	 */
	public static CarActType daHuaActType(int actType){
		return actType == 0 ? CarActType.longTerm : actType == 2 ? CarActType.freeCar : CarActType.temporary;
	}

	// 大华停车标识设置 为了直观观测数据准确性 可以注释掉
	public static String inOutBizSn(String inBizSn, String bizSn){
		if (inBizSn == null || inBizSn.length() == 0) {
			char[] cs = new char[bizSn.length()];
			for (int i = 0; i < bizSn.length(); i++)
				cs[i] = '0';
			bizSn = String.valueOf(cs) + ":" + bizSn;
		} else {
			if (!bizSn.equals(inBizSn))
				bizSn = inBizSn + ":" + bizSn;
		}
		return bizSn;
	}
}
